use std::{fs::File, io::Read};
use lazy_static::lazy_static;
use serde::Deserialize;

use serde_json::{json, Value};
use std::fs;
use sqlx;
use std::env;
use sqlx::postgres::PgRow;
use sqlx::{postgres::PgPoolOptions, Executor, postgres::PgPool,Row};
use sqlx::FromRow;

#[derive(Debug, serde::Deserialize)]
pub struct PostgreSQL {
    pub db_name: String,
    pub db_host: String,
    pub db_port: String,
    pub db_user: String,
    pub db_password: String,
    pub max_connections: u32,
}

#[derive(Debug, Deserialize)]
pub struct Options {
    pub odoo_version: String,
    pub load_language: String,
    pub pg_path: String,
    pub admin_passwd: String,
}

#[derive(Debug, Deserialize)]
pub struct Setting {
    pub database: PostgreSQL,
    pub options: Options,
}


impl Default for Setting {
    fn default() -> Self {
        let file_path = "config.toml";
        let mut file = match File::open(file_path) {
            Ok(f) => f,
            Err(e) => panic!("error is op en config {e}")
        };

        let mut str = String::new();
        // println!("{}",str);
        match file.read_to_string(&mut str) {
            Ok(s) => s,
            Err(e) => panic!("error read str {}", e)
        };

        toml::from_str(&str).expect("Parsing the configuration file failed")
    }
}

impl Setting {
    pub fn get<'a>() -> &'a Self {
        lazy_static! {
            static ref CACHE : Setting = Setting::default();
        }
        &CACHE
    }
}

// pub fn read_toml() -> Setting {
//     let setting = Setting::default();
//     // println!("{:#?}",setting);
//     // Setting::get();
//     // let c = Setting::get();
//     // println!("返回整个配置:{:#?}", c);
//     // println!("调用的字段:{:#?}", setting.database.admin_passwd);
//     Setting {
//         database: setting.database,
//         options: setting.options,
//     }
// }
//
//
// /// pgsql连接
// pub async fn pgsql_conn() -> sqlx::Result<PgPool> {
//     // 根据实际数据库配置修改
//     let c = read_toml();
//     let db_name = c.database.db_name;
//     let db_host = c.database.db_host;
//     let db_port = c.database.db_port;
//     let db_user = c.database.db_user;
//     let db_password = c.database.db_password;
//     let max_connections = c.database.max_connections;
//
//     let conn_str =&format!(
//         "postgres://{}{}{}@{}{}{}{}{}",
//         db_user,
//         if db_password.is_empty(){""}else{":"},
//         db_password,
//         db_host,
//         if db_port.is_empty(){""}else{":"},
//         db_port,
//         if db_name.is_empty(){""}else{"/"},
//         db_name
//     );
//
//     println!("数据库URL: {}", conn_str);
//
//     // let str ="postgres://odoo:123456@localhost:5432/odoo17";
//     PgPoolOptions::new().max_connections(max_connections).connect(conn_str).await
// }